import { Controller, Inject, Get, Post, Body } from '@midwayjs/core'
import { AdminsService } from '../../service/admin/AdminsService'
import { BaseController } from '../base.chontroller'

@Controller('/admins')
export class AdminsController extends BaseController {
  @Inject()
  service!: AdminsService

  @Get('/list')
  async list() {
    try {
      const data = await this.service.list()
      return this.success<IList<any>>(data)
    } catch (err: any) {
      return this.fail(err.message || '获取列表失败')
    }
  }

  @Post('/add')
  async add(@Body() data: any) {
    if (!data?.phone || !data?.name || !data?.password) {
      return this.fail('缺少必要参数')
    }
    try {
      const result = await this.service.add(data)
      return this.success(result, '添加成功')
    } catch (err: any) {
      return this.fail(err.message || '添加失败')
    }
  }

  @Post('/edit')
  async edit(@Body() data: any) {
    if (!data?.id) {
      return this.fail('缺少ID参数')
    }
    try {
      const result = await this.service.edit(data)
      return this.success(result, '编辑成功')
    } catch (err: any) {
      return this.fail(err.message || '编辑失败')
    }
  }

  @Post('/delete')
  async delete(@Body() data: any) {
    if (!data?.id) {
      return this.fail('缺少ID参数')
    }
    try {
      await this.service.delete(data.id)
      return this.success(null, '删除成功')
    } catch (err: any) {
      return this.fail(err.message || '删除失败')
    }
  }

  // 登录
  @Post('/login')
  async login(@Body() data: any) {
    console.log(data);
    
    if (!data?.username || !data?.password) {
      return this.fail('缺少必要参数')
    }
    try {
      const result = await this.service.login(data)
      return this.success(result, '登录成功')
    } catch (err: any) {
      return this.fail(err.message || '登录失败')
    }
  }

  // 登出
  @Post('/logout')
  async logout() {
    try {
      await this.service.logout()
      return this.success(null, '登出成功')
    } catch (err: any) {
      return this.fail(err.message || '登出失败')
    }
  }
}
